package com.weirblog.resource;

import io.quarkus.hibernate.orm.panache.PanacheEntityBase;
import io.quarkus.hibernate.orm.panache.PanacheQuery;
import io.quarkus.mailer.Mail;
import io.quarkus.mailer.reactive.ReactiveMailer;
import io.quarkus.qute.Location;
import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateInstance;

import com.weirblog.entity.Tmenu;
import com.weirblog.entity.Users;
import com.weirblog.entity.permission.PermUserRole;
import com.weirblog.vo.DataGrid;
import com.weirblog.vo.JsonVO;

import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.stream.Collectors;

import javax.annotation.security.RolesAllowed;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.StringUtils;

@Path("user")
@ApplicationScoped
public class UsersResource {

	@GET
	@Path("list")
	public DataGrid<Users> list(@QueryParam("page") Integer page, @QueryParam("rows") Integer rows) {
		PanacheQuery<PanacheEntityBase> panacheQuery = Users.findAll().page(page-1, rows);
		DataGrid<Users> dataGrid = new DataGrid<Users>(panacheQuery.count(), panacheQuery.list());
		return dataGrid;
	}

	@GET
	@Path("{id}")
	public Users getSingle(@PathParam("id") Long id) {
		Users entity = Users.findById(id);
		if (entity == null) {
			return new Users();
		}
		return entity;
	}

	@Inject
	ReactiveMailer reactiveMailer;

	@GET
	@Path("/email")
	public CompletionStage<Response> sendASimpleEmailAsync() {
		return reactiveMailer
				.send(Mail.withText("weiwei0620@qq.com", "A reactive email from quarkus", "This is my body"))
				.subscribeAsCompletionStage().thenApply(x -> Response.accepted().build());
	}
	
	@Location("admin/userRole.html")
	Template userRole;

	@GET
	@Path("roleUI/{id}")
	@Produces(MediaType.TEXT_HTML)
	public TemplateInstance userRole(@PathParam("id") Integer id) {
		List<PermUserRole> list = PermUserRole.find("user_id", id).list();
		List<Integer> roleIds = list.stream().map(PermUserRole::getRoleId).collect(Collectors.toList());
		Users users = new Users();
		users.id = id;
		users.roleIds = StringUtils.join(roleIds, ",");
		return userRole.data("user", users);
	}
	@RolesAllowed("user_role")
//	@PermitAll
	@POST
	@Path("role")
	@Transactional
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public JsonVO<Tmenu> add(@FormParam("userId") Integer userId, 
			@FormParam("roleIds") String roleIds) {
		JsonVO<Tmenu> j = new JsonVO<>();
		if (userId == null || userId < 0) {
			j.setCode(1);
			j.setMsg("用户ID不能为空或负数");
			j.setSuccess(false);
			return j;
		}
		Users user = Users.findById(userId);
		if (user == null) {
			j.setCode(1);
			j.setMsg("用户不存在");
			j.setSuccess(false);
			return j;
		}
		
		PermUserRole.delete("user_id", userId);
		if (StringUtils.isNotBlank(roleIds)) {
			String[] rIds = StringUtils.split(roleIds, ",");
			for (String rId : rIds) {
				new PermUserRole(userId, Integer.valueOf(rId)).persist();
			}
		}
		
		j.setMsg("添加或修改成功");
		j.setSuccess(true);
		return j;
	}

}
